//
//  MGTabPageBar.m
//  Mango
//
//  Created by 胡超 on 2020/6/29.
//  Copyright © 2020 HuChao. All rights reserved.
//

#import "MGTabPageBar.h"
#import "MGGradientEdgeView.h"
#import "UIImage+Mango.h"
#import "UIView+Mango.h"

@interface MGTabPageBar() {
    MGTabPageBarStyle *_style;
    MGGradientEdgeView *_scrollEdgeView;
    UIScrollView *  _scrollView;
    NSMutableArray *_itemButtons;
    UIImageView *   _indicatorView;
    
    __weak UIButton *_selectedItemButton;
    
    BOOL _didAddExtraItem;
    CGSize _extraItemSize;
    CGFloat _extraItemSpace;
    CGFloat _nextExtraItemRight;
    NSMutableArray *_extraItems;
}

@end

@implementation MGTabPageBar

- (instancetype)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame style:nil];
}

- (instancetype)initWithFrame:(CGRect)frame style:(MGTabPageBarStyle *)style {
    if (self = [super initWithFrame:frame]) {
        _style = style ?: [[MGTabPageBarStyle alloc] init];
        _itemButtons = [[NSMutableArray alloc] init];
        _selectedItemIndex = 0;
        _extraItems = [[NSMutableArray alloc] init];
        _extraItemSize = CGSizeMake(44, 44);
        _extraItemSpace = 5;
        _nextExtraItemRight = self.width-_style.contentInsets.right;
        
        if (_style.layoutType == MGTabLayoutTypeAutoScroll) {
            _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
            _scrollView.showsVerticalScrollIndicator = NO;
            _scrollView.showsHorizontalScrollIndicator = NO;
            if (@available(iOS 11.0, *)) {
                _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            }
            
            _scrollEdgeView = [[MGGradientEdgeView alloc] initWithFrame:self.bounds];
            [_scrollEdgeView addScrollView:_scrollView mode:MGGradientEdgeModeLeftRight edgeWidth:20 autoHide:YES];
            [self addSubview:_scrollEdgeView];
        }
        
        if (_style.showIndicatorView) {
            _indicatorView = [[UIImageView alloc] init];
            _indicatorView.hidden = YES;
            [self.contentView addSubview:_indicatorView];
        }
    }
    return self;
}

- (UIView *)contentView {
    if (_style.layoutType == MGTabLayoutTypeAutoScroll) {
        return _scrollView;
    } else {
        return self;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (_didAddExtraItem) {
        _scrollEdgeView.height = self.height;
    } else {
        _scrollEdgeView.frame = self.bounds;
    }
}

- (void)setExtraItemSize:(CGSize)itemSize space:(CGFloat)space {
    _extraItemSize = itemSize;
    _extraItemSpace = space;
}

- (void)addExtraItem:(UIImage *)image target:(id)target selector:(SEL)selector {
    [self addExtraItem:image size:_extraItemSize target:target selector:selector];
}

- (void)addExtraItem:(UIImage *)image size:(CGSize)size target:(id)target selector:(SEL)selector {
    UIButton *button = [[UIButton alloc] init];
    [button setSize:size];
    [button setRight:_nextExtraItemRight];
    [button setCenterY:self.height/2];
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
    [_extraItems addObject:button];
    _didAddExtraItem = YES;
    _nextExtraItemRight = button.left-_extraItemSpace;
    
    if (_style.layoutType == MGTabLayoutTypeAutoScroll) {
        _scrollEdgeView.width = button.left-10;
    }
}

- (void)setSelectedItemIndex:(NSInteger)selectedItemIndex {
    [self setSelectedItemIndex:selectedItemIndex animated:YES];
}

- (void)setSelectedItemIndex:(NSInteger)selectedItemIndex animated:(BOOL)animated {
    if (_items.count == 0)
        return;
    
    _selectedItemIndex = selectedItemIndex;
    if (_selectedItemIndex < 0 || _selectedItemIndex >= _itemButtons.count) {
        _selectedItemIndex = 0;
    }
    UIButton *itemButton = _itemButtons[selectedItemIndex];
    CGFloat scale = _style.selectedItemScale;
    _selectedItemButton.selected = NO;
    _selectedItemButton.userInteractionEnabled = YES;
    [UIView animateWithDuration:animated?0.15:0 animations:^{
        _selectedItemButton.transform = CGAffineTransformIdentity;
    }];
    _selectedItemButton = itemButton;
    _selectedItemButton.selected = YES;
    _selectedItemButton.userInteractionEnabled = NO;
    [UIView animateWithDuration:animated?0.15:0 animations:^{
        _selectedItemButton.transform = CGAffineTransformMakeScale(scale, scale);
    }];
    [self moveIndicatorViewToItem:itemButton animated:animated];
    
    if ([self.delegate respondsToSelector:@selector(tabPageBar:didSelectItemAtIndex:)]) {
        [self.delegate tabPageBar:self didSelectItemAtIndex:selectedItemIndex];
    }
}

- (void)setItems:(NSArray<NSString *> *)items {
    if (_items.count > 0) {
        [_itemButtons makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [_itemButtons removeAllObjects];
    }
    
    _items = items;
    for (NSInteger i=0; i<items.count; i++) {
        NSString *title = items[i];
        UIButton *itemButton = [[UIButton alloc] init];
        [itemButton.titleLabel setFont:_style.titleFont];
        [itemButton setTitle:title forState:UIControlStateNormal];
        [itemButton setTitleColor:_style.normalTintColor forState:UIControlStateNormal];
        [itemButton setTitleColor:_style.selectTintColor forState:UIControlStateSelected];
        [itemButton setTag:i];
        [itemButton addTarget:self action:@selector(onItemButton:) forControlEvents:UIControlEventTouchUpInside];
        [_itemButtons addObject:itemButton];
        [self.contentView addSubview:itemButton];
    }
    [self layoutWithStyle];
    // 设置初始选中状态
    [self setSelectedItemIndex:_selectedItemIndex animated:NO];
}

- (void)layoutWithStyle {
    if (_items.count == 0)
        return;
    
    switch (_style.layoutType) {
        case MGTabLayoutTypeLeft:       [self layoutWithLeft]; break;
        case MGTabLayoutTypeAutoScroll: [self layoutWithAutoScroll]; break;
        case MGTabLayoutTypeCenter:
        case MGTabLayoutTypeRight:
        case MGTabLayoutTypeFlexible:   [self layoutWithFlexible]; break;
            
        default:
            break;
    }

    if (_style.showIndicatorView) {
        _indicatorView.hidden = NO;
        _indicatorView.height = _style.indicatorHeight;
        _indicatorView.bottom = self.height+_style.indicatorOffset.height;
        _indicatorView.layer.cornerRadius = _style.indicatorCornerRadius;
        _indicatorView.layer.masksToBounds = YES;
        if (_style.indicatorImage) {
            _indicatorView.image = _style.indicatorImage;
        } else if (_style.indicatorTintColor) {
            _indicatorView.backgroundColor = _style.indicatorTintColor;
        } else {
            _indicatorView.backgroundColor = _style.selectTintColor;
        }
    }
}

- (void)layoutWithLeft {
    CGFloat count = _itemButtons.count;
    UIEdgeInsets insets = _style.contentInsets;
    CGFloat space = _style.itemSpace;
    CGFloat titlePadding = _style.titlePadding;
    CGFloat height = self.height-insets.top-insets.bottom;
    CGFloat x = insets.left;
    for (UIButton *itemButton in _itemButtons) {
        [itemButton sizeToFit];
        [itemButton setSize:CGSizeMake(itemButton.width+titlePadding*2, height)];
        [itemButton setOrigin:CGPointMake(x, insets.top)];
        x = itemButton.right+space;
        if (_scrollView) {
            _scrollView.contentSize = CGSizeMake(itemButton.right+insets.right, 0);
        }
    };
}

- (void)layoutWithAutoScroll {
    [self layoutWithLeft];
}

- (void)layoutWithFlexible {
    CGFloat count = _itemButtons.count;
    UIEdgeInsets insets = _style.contentInsets;
    CGFloat space = _style.itemSpace;
    CGFloat width = (self.width-space*(count-1)-insets.left-insets.right) / count;
    CGFloat height = self.height-insets.top-insets.bottom;
    [_itemButtons enumerateObjectsUsingBlock:^(UIButton *itemButton, NSUInteger idx, BOOL * stop) {
        itemButton.frame = CGRectMake(insets.left+(width+space)*idx, insets.top, width, height);
    }];
}

- (void)onItemButton:(UIButton *)sender {
    self.selectedItemIndex = sender.tag;
}

- (void)moveIndicatorViewToItem:(UIButton *)item animated:(BOOL)animated {
    if (!item) {
        return;
    }

    CGFloat indicatorWidth = 0;
    switch (_style.indicatorType) {
        case MGTabIndicatorTypeFixedWidth:
            indicatorWidth = _style.indicatorWidth;
            break;
        case MGTabIndicatorTypeItemWidth:
            indicatorWidth = item.width;
            break;
    }
    
    indicatorWidth += (_style.indicatorOffset.width*2);
    [UIView animateWithDuration:animated?0.15:0.0 animations:^{
        _indicatorView.width = indicatorWidth;
        _indicatorView.centerX = item.centerX;
        
        if (_style.layoutType == MGTabLayoutTypeAutoScroll) {
            if (item.tag == 0) {
                if (item.left < _scrollView.contentOffset.x) {
                    _scrollView.contentOffset = CGPointZero;
                }
            } else if (item.tag == _itemButtons.count-1) {
                if (item.right > _scrollView.contentOffset.x+_scrollView.width) {
                    _scrollView.contentOffset = CGPointMake(_scrollView.contentSize.width-_scrollView.width, 0);
                }
            } else {
                UIButton *prevItem = _itemButtons[item.tag-1];
                UIButton *nextItem = _itemButtons[item.tag+1];
                if (prevItem.left < _scrollView.contentOffset.x) {
                    _scrollView.contentOffset = CGPointMake(prevItem.left, 0);
                } else if (nextItem.right > _scrollView.contentOffset.x+_scrollView.width) {
                    _scrollView.contentOffset = CGPointMake(nextItem.right-_scrollView.width, 0);
                }
            }
        }
    }];
//    CGFloat indicatorWidth = 0;
//    switch (_style.indicatorType) {
//        case MGTabIndicatorTypeFixedWidth:
//            break;
//        case FXActivityTypeKeepItemTitleWidth: {
//            NSString *title = [item titleForState:UIControlStateNormal];
//            CGFloat titleWidth = ceil([title sizeWithAttributes:@{NSFontAttributeName:_itemTextFont}].width) * _selectedItemScale;
//            activityWidth = titleWidth;
//            break;
//        }
//        case FXActivityTypeKeepItemWidth:
//            activityWidth = item.frame.size.width;
//            break;
//        case FXActivityTypeKeepFixedWidth:
//        default:
//            activityWidth = _activityWidth;
//            break;
//    }
//
//    activityWidth += (_activityOffset.width*2);
//    [UIView animateWithDuration:animated?0.15:0.0 animations:^{
//        UIView *activityView = self->_activityView;
//        UIScrollView *scrollView = self->_scrollView;
//        CGSize activityOffset = self->_activityOffset;
//        NSArray *itemButtons = self->_itemButtons;
//        activityView.size = CGSizeMake(activityWidth, activityHeight);
//        activityView.centerX = item.centerX;
//        activityView.bottom = scrollView.height+activityOffset.height;
//        if (self.autoScrollItem) {
//            if (item.tag == 0) {
//                if (item.left < scrollView.contentOffset.x) {
//                    scrollView.contentOffset = CGPointZero;
//                }
//            } else if (item.tag == itemButtons.count-1) {
//                if (item.right > scrollView.contentOffset.x+scrollView.width) {
//                    scrollView.contentOffset = CGPointMake(scrollView.contentSize.width-scrollView.width, 0);
//                }
//            } else {
//                UIButton *prevItem = itemButtons[item.tag-1];
//                UIButton *nextItem = itemButtons[item.tag+1];
//                if (prevItem.left < scrollView.contentOffset.x) {
//                    scrollView.contentOffset = CGPointMake(prevItem.left, 0);
//                } else if (nextItem.right > scrollView.contentOffset.x+scrollView.width) {
//                    scrollView.contentOffset = CGPointMake(nextItem.right-scrollView.width, 0);
//                }
//            }
//        }
//    }];
}

#pragma mark - SetProperty

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//    [self updateWithProperties];
}

@end
